﻿using System.Windows.Input;
using DDU.DataModel;
using DDU.Library;

namespace DDU.ViewModel
{
    public class VacationAddViewModel : MainViewModel
    {
        public VacationAddViewModel()
        {
            VacationToAdd.ValueChanged -= VacationToAdd_ValueChanged;
            VacationToAdd.ValueChanged += VacationToAdd_ValueChanged;
        }

        void VacationToAdd_ValueChanged(object sender, PropertyArgs e)
        {
            RaisePropertyChanged(() => TimeError);
            RaisePropertyChanged(() => AddCommand);
        }

        private VacationInfo vacationToAdd = new VacationInfo();
        public VacationInfo VacationToAdd
        {
            get { return vacationToAdd; }
            set
            {
                vacationToAdd = value;
                RaisePropertyChanged(() => VacationToAdd);
                RaisePropertyChanged(() => TimeError);

                VacationToAdd.ValueChanged -= VacationToAdd_ValueChanged;
                VacationToAdd.ValueChanged += VacationToAdd_ValueChanged;
            }
        }

        public bool TimeError
        {
            get { return VacationToAdd.StartTime > VacationToAdd.EndTime; }
        }

        private void Insert(VacationInfo entity)
        {
            Database.CollectionOfVacations.InsertOnSubmit(entity);
            Submit();
            VacationToAdd = new VacationInfo();
            RaisePropertyChanged(() => VacationToAdd);
            RaisePropertyChanged(() => TimeError);
            RaisePropertyChanged(() => AddCommand);

            VacationToAdd.ValueChanged -= VacationToAdd_ValueChanged;
            VacationToAdd.ValueChanged += VacationToAdd_ValueChanged;

        }

        public ICommand AddCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrWhiteSpace(VacationToAdd.Title) && !TimeError; },
                    ExecuteCallback = delegate
                    {
                        Insert(VacationToAdd);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Navigate(BackUri);
                    }
                };
            }
        }
    }
}
